// mircoApp/map_labeling/store_location/store_location.js
var app = getApp();
var _location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [_location],

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    status_array: [],
    edit_button: false,
    fileList1: [],
    fileList2: [],
    fileList3: [],
    location: "",
    store_name: "",
    operate_address: "",
    store_address: "",
    storefront_imgs: [],
    nearby_imgs: [],
    in_store_imgs: [],

    address_mark: "",
    mobile: "",
    fixed_line: "",
    addressInfo: "",
    remark: "",

    hoursShow: false,
    workWeek: [
      //显示选中的日期数组
      {
        title: "周一",
        value: "1",
        checked: false
      },
      {
        title: "周二",
        value: "2",
        checked: false
      },
      {
        title: "周三",
        value: "3",
        checked: false
      },
      {
        title: "周四",
        value: "4",
        checked: false
      },
      {
        title: "周五",
        value: "5",
        checked: false
      },
      {
        title: "周六",
        value: "6",
        checked: false
      },
      {
        title: "周日",
        value: "7",
        checked: false
      }
    ],
    form: {
      work_week: "",
      work_start_time: "",
      work_end_time: "",

    },
    is_show_status: false,
    currentTime: "0:00",
    startTime: "0:00",
    endTime: "0:00",
    point: {},
    businessHours: "",
    msg: "",
    id: '',
    readonly: false,
    timeState:1, //判断是选择开始时间还是结束时间
    startTimeArr:[],
    timeArrValue:[0,0], //重置时间选择
    endTimeArr:[],
    beginHour: "00",
    beginMinute: "00",
    endHour: "00",
    endMinute: "00",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      hoursShow: false
    })
    let id = options.id || wx.getStorageSync('map_marker_id') || '';
    this.setData({id})
    if (id) {
      this.setData({readonly:true});
      this.getDetail()
    } else {
      let address_point = wx.getStorageSync('address-point') || wx.getStorageSync('applyaddresspoint');
      if(address_point){
        this.setData({
          point:address_point.point,
          location_txt: `经度${address_point.point.lng},纬度${address_point.point.lat}`,
        })
        return;
      }
        this._getLocation((mapdata, e) => {
          let point = app.qqMapTransBMap(parseFloat(mapdata.location.lng), parseFloat(mapdata.location.lat));
          this.setData({
            point: point,
            location_txt: `经度${point.lng},纬度${point.lat}`,
          });
        });
    }
  },

  edit() {
    this.setData({
      is_show_status:true,
      readonly:false,
    })
  },

  afterRead_t(event) {
    wx.showLoading({
      title: '上传中',
    })
    let {
      file
    } = event.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      formData: null,
      success: (res) => {
        let {result,msg,data} = JSON.parse(res.data);
        wx.hideLoading();
        this.data.storefront_imgs.push(data.img_url)
        this.data.fileList1.push({url:data.img_url,...file});
        this.setData({
          fileList1:this.data.fileList1,
          storefront_imgs:this.data.storefront_imgs
        })
      },
      fail: (err) => {
        wx.hideLoading()
      }
    });
  },
  toGeolocation() {
    if (this.data.readonly) {
      return;
    }
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=idShopApply'
    });
  },

  getDetail() {
    this.setData({
      fileList1:[],
      fileList2:[],
      fileList3:[]
    })
    app._postNetWork({
      url: app.getNetAddresss("plugin.map-marker.frontend.controllers.marker.list.details"),
      data: {
        id: this.data.id
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result) {
          this.setData({
            edit_button :data.edit_button,
            businessHours :data.businessHours,
            status_array :data.status_array,
            store_name :data.store_name,
            operate_address :data.operate_address,
            store_address :data.store_address,
            address_mark :data.address_mark,
            businessHours :data.operate_time,
            mobile :data.mobile,
            point:{lng:data.location.split(',')[0],lat:data.location.split(',')[1]},
            location_txt:`经度${data.location.split(',')[0]},纬度${data.location.split(',')[1]}`,
            fixed_line :data.fixed_line,
            remark :data.remark,
            storefront_imgs :data.storefront_imgs,
            in_store_imgs :data.in_store_imgs,
            nearby_imgs :data.nearby_imgs
          })
        

          data.storefront_imgs.forEach(item => {
            this.data.fileList1.push({
              url: item
            })
          })
          data.in_store_imgs.forEach(item => {
            this.data.fileList2.push({
              url: item
            })
          })
          data.nearby_imgs.forEach(item => {
            this.data.fileList3.push({
              url: item
            })
          })
          this.setData({
            fileList3:this.data.fileList3,fileList2:this.data.fileList2,fileList1:this.data.fileList1
          })
          if(data.status_array&&data.status_array.length==1&&data.status_array[0].code == 1){
            this.setData({readonly: true})
          }
          let _res = data.status_array.filter(item => item.code == 0);
          if (_res && _res.length !== 0) {
            this.setData({
              readonly: true,
              msg: _res[0].msg
            })
          }
        } else {
          app.tips(msg);
        }
      }
    })
  },
  delete_1(e){
    this.data.fileList1.splice(e.detail.index,1);
    this.data.storefront_imgs.splice(e.detail.index,1);
    this.setData({fileList1:this.data.fileList1,storefront_imgs:this.data.storefront_imgs});
  },
  delete_2(e){
    this.data.fileList2.splice(e.detail.index,1);
    this.data.in_store_imgs.splice(e.detail.index,1);
    this.setData({fileList2:this.data.fileList2,in_store_imgs:this.data.in_store_imgs});
  },
  delete_3(e){
    this.data.fileList3.splice(e.detail.index,1);
    this.data.nearby_imgs.splice(e.detail.index,1);
    this.setData({fileList3:this.data.fileList3,nearby_imgs:this.data.nearby_imgs});
  },
  bindChangeTime(event) {
    const val = event.detail.value;
    let startTimeArr = this.data.startTimeArr; //开始时间
    let endTimeArr = this.data.endTimeArr; //结束时间
    if(this.data.timeState === 1) {
      this.setData({
        beginHour:startTimeArr[val[0]],
        beginMinute: endTimeArr[val[1]]
      })
    }
    if(this.data.timeState === 2) {
      this.setData({
        endHour:startTimeArr[val[0]],
        endMinute: endTimeArr[val[1]]
      })
    }
  },

  workWeekOn(event) {
    let index = event.currentTarget.dataset.index;
    let workWeekData = this.data.workWeek;
    workWeekData[index].checked = !workWeekData[index].checked;//修改选中的星期几
    this.setData({
      workWeek:workWeekData
    })
  },
  chooseTimeOn(event){ //切换开始和结束时间
    let state = event.currentTarget.dataset.state;
    this.setData({
      timeArrValue: [0,0]
    })
    this.setData({
      timeState:Number(state)
    })
  },
  show_hours() {
    if (this.data.readonly) {
      return;
    }
    let startTimeArr = [];
    let endTimeArr = [];
    for(let i=0; i<24; i++) {
      i < 10 ? i = '0'+ i : i;
      startTimeArr.push(i)
    }
    for(let j=0; j<=59; j++) {
      j < 10 ? j = '0'+ j : j;
      endTimeArr.push(j)
    }
    this.setData({
      hoursShow:true,
      startTimeArr:startTimeArr,
      endTimeArr:endTimeArr
    })
  },
  submit() {
    let json = {
      form: {
        store_name: this.data.store_name,
        location: `${this.data.point.lng},${this.data.point.lat}`,
        storefront_imgs: this.data.storefront_imgs,
        in_store_imgs: this.data.in_store_imgs,
        nearby_imgs: this.data.nearby_imgs,
        remark: this.data.remark,
        fixed_line: this.data.fixed_line,
        mobile: this.data.mobile,
        operate_time: this.data.businessHours,
        address_mark: this.data.address_mark,
        store_address: this.data.store_address,
        operate_address: this.data.operate_address
      }
    };
    let url = "plugin.map-marker.frontend.controllers.apply.index";
    if (this.data.id) {
      url = 'plugin.map-marker.frontend.controllers.apply.index.edit'
      json.id = this.data.id;
    }
    app._postNetWork({
      url:app.getNetAddresss(url),
      data:json,
      success:resdata=>{
        let {result,msg,data} = resdata.data;
        app.tips(msg);
        if(data.id){
          wx.setStorageSync('map_marker_id', data.id)
          this.setData({id:data.id});
        }
        setTimeout(() => {
          if(result){
            this.setData({is_show_status: false});
            this.getDetail()
          }else{
            if(data.push_error){
              this.setData({is_show_status: false});
              this.getDetail()
            }
          }
     
        }, 500);
      }
    })
   
  },
  onAffirm(event) {
    let  workWeek = this.data.workWeek,
       startTime = `${this.data.beginHour}:${this.data.beginMinute}`,
       endTime =  `${this.data.endHour}:${this.data.endMinute}`,
       startDate = '',
       endDate = '',
       workData = [],
       workIdData = [];
   workData = workWeek.filter(item => { //筛选所有选中的日期
     return  item.checked === true?item.value:false;
   });
   if(workData.length > 0) {
     if(Number(this.data.beginHour) < Number(this.data.endHour)) {  //记得加选择日期 
       workData.forEach((item) => {
         workIdData.push(item.value);
       });
       startDate = workData[0].title;
       endDate = workData[workData.length -1].title;
       this.setData({
         'form.work_week':workIdData,
         'form.work_start_time':startTime,
         'form.work_end_time':endTime,
         businessHours:`${startDate}至${endDate} ${startTime}-${endTime}`,
         hoursShow: false
       })
     } else {
       wx.showToast({
         icon: 'none',
         title: '结束时间不能大于开始时间',
         duration: 1500
       });
     }
   } else {
     wx.showToast({
       icon: 'none',
       title: '请选择店铺营业日期',
       duration: 1500
     });
   }
 },

 onClose(event) {
  let type = event.currentTarget.dataset.type;
  if(type === 'hours') {
    this.setData({
      hoursShow:false
    })
  } else {
    this.setData({
      classifyShow:false
    })
  }
},

  afterRead(event) {
    wx.showLoading({
      title: '上传中',
    })
    let {
      file
    } = event.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      formData: null,
      success: (res) => {
        let {result,msg,data} = JSON.parse(res.data);
        wx.hideLoading();
        this.data.in_store_imgs.push(data.img_url)
        this.data.fileList2.push({url:data.img_url,...file});
        this.setData({
          fileList2:this.data.fileList2,
          in_store_imgs:this.data.in_store_imgs
        })
      },
      fail: (err) => {
        wx.hideLoading()
      }
    });
  },

  afterRead_1(event) {
    wx.showLoading({
      title: '上传中',
    })
    let {
      file
    } = event.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      formData: null,
      success: (res) => {
        let {result,msg,data} = JSON.parse(res.data);
        wx.hideLoading();
        this.data.nearby_imgs.push(data.img_url)
        this.data.fileList3.push({url:data.img_url,...file});
        this.setData({
          fileList3:this.data.fileList3,
          nearby_imgs:this.data.nearby_imgs
        })
      },
      fail: (err) => {
        wx.hideLoading()
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let address_point = wx.getStorageSync('address-point') || wx.getStorageSync('applyaddresspoint');
    if(address_point){
      this.setData({
        point:address_point.point,
        location_txt: `经度${address_point.point.lng},纬度${address_point.point.lat}`
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if(wx.getStorageSync('map_marker_id')){
      wx.removeStorageSync('map_marker_id')
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})